import { login, getMenu, logout, checkLogin, getRoutes, getInfo, changeMenu } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";

const state = {
  token: getToken(),
  name: "",
  avatar: "",
  introduction: "",
  roles: [],
  role_id: "",
  btnQx: {},
  loginFlag: 0,
  // 用户id
  id: "",
  // 用户部门对象
  userDept: [],
  // 用户信息组件
  userInfo: {}
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_LOGIN_FLAG: (state, flag) => {
    state.loginFlag = flag;
  },
  SET_ROLE_ID: (state, id) => {
    state.role_id = id;
  },
  SET_BTNQX: (state, data) => {
    state.btnQx = data;
  },
  SET_ID: (state, data) => {
    state.id = data;
  },
  SET_USER_DEPT: (state, data) => {
    state.userDept = data;
  },
  SET_USER_INFO: (state, data) => {
    state.userInfo = data;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ userCode: username.trim(), password: password.trim() }).then(response => {
        const { data } = response;
        // commit('SET_TOKEN', data.token)
        setToken(data.token);
        resolve(response);
      }).catch(error => {
        reject(error);
      });
    });
  },
  /**
   * @name getMenu
   * @description 获取菜单
   * @author cjs1992
   * @date 2019-09-04 09:51:33
   */
  getMenu({ commit, state }, data) {
    return new Promise((resolve, reject) => {
      getMenu(data).then((res) => {
        resolve(res);
      }).catch((error) => {
        reject(error);

      });
    });
  },
  /**
   * @name setInfo
   * @description 设置基础信息
   * @author cjs1992
   * @date 2019-12-02 13:47:51
   */
  setInfo({ commit, state }, data) {
    const { name, roles, role_id, buttons = [], id, userDept = {}, userInfo = {}} = data;
    name !== undefined ? commit("SET_NAME", name) : null;
    roles !== undefined ? commit("SET_ROLES", roles) : null;
    role_id !== undefined ? commit("SET_ROLE_ID", role_id) : null;
    id !== undefined ? commit("SET_ID", id) : null;
    let obj = {} // eslint-disable-line
    buttons.map((item) => { item.ischeck === 1 ? obj[item.route] = 1 : null; });

    commit("SET_BTNQX", obj);
    commit("SET_USER_DEPT", userDept);
    commit("SET_USER_INFO", userInfo);

  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response;

        if (!data) {
          reject("Verification failed, please Login again.");
        }

        const { roles, name, avatar, introduction } = data;

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject("getInfo: roles must be a non-null array!");
        }

        commit("SET_ROLES", roles);
        commit("SET_NAME", name);
        commit("SET_AVATAR", avatar);
        commit("SET_INTRODUCTION", introduction);
        resolve(data);
      }).catch(error => {
        reject(error);
      });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout({}).then((res) => {
        resolve(res);
      }).catch((err) => { reject(err); });
    });
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     commit('SET_TOKEN', '')
    //     commit('SET_ROLES', [])
    //     removeToken()
    //     resetRouter()
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },
  checkLogin({ commit, state }) {
    return new Promise((resolve, reject) => {
      checkLogin().then((res) => {
        if (res.status === 1000) {
          // 验证通过
          commit("SET_LOGIN_FLAG", 1);
        } else {
          // 验证不通过
          commit("SET_LOGIN_FLAG", 0);
        }
        resolve(res);
      }).catch((err) => { reject(err); });
    });
  },
  getRoutes({ commit, state }, data) {
    return new Promise((resolve, reject) => {
      getRoutes(data).then((res) => {
        resolve(res);
      }).catch((err) => { reject(err); });
    });
  },
  changeMenu({ commit }, data) {
    return new Promise((resolve, reject) => {
      changeMenu(data).then((res) => {
        resolve(res);
      }).catch((err) => { reject(err); });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resolve();
    });
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + "-token";

      commit("SET_TOKEN", token);
      setToken(token);

      const { roles } = await dispatch("getInfo");

      resetRouter();

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch("permission/generateRoutes", roles, { root: true });

      // dynamically add accessible routes
      router.addRoutes(accessRoutes);

      // reset visited views and cached views
      dispatch("tagsView/delAllViews", null, { root: true });

      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
